package com.nuc.seckill.security.filter;

import cn.hutool.core.io.IoUtil;
import cn.hutool.core.util.CharsetUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.nuc.seckill.exception.ErrorMessage;
import com.nuc.seckill.security.exception.BaseAuthenticationException;
import org.springframework.http.MediaType;
import org.springframework.security.authentication.AuthenticationServiceException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;


/**
 * @author spider
 */
public class JsonUsernamePasswordFilter extends UsernamePasswordAuthenticationFilter {

    /**
     * 校验请求方式及参数
     *
     * @param request  请求
     * @param response 响应
     * @return org.springframework.security.core.Authentication
     * @author 石一歌
     * @date 2022/8/9 23:37
     */
    @Override
    public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException {
        if (!"POST".equals(request.getMethod())) {
            throw new AuthenticationServiceException(
                    "Authentication method not supported: " + request.getMethod());
        }
        if (request.getContentType().startsWith(MediaType.APPLICATION_JSON_VALUE)) {
            UsernamePasswordAuthenticationToken authRequest;
            try (InputStream is = request.getInputStream()) {
                String body = IoUtil.read(is, CharsetUtil.CHARSET_UTF_8);
                JSONObject jsonObject = JSON.parseObject(body);
                String username = jsonObject.getJSONObject("data").getString("username");
                String password = jsonObject.getJSONObject("data").getString("password");
                authRequest = new UsernamePasswordAuthenticationToken(username, password);
                setDetails(request, authRequest);
                return this.getAuthenticationManager().authenticate(authRequest);
            } catch (IOException e) {
                e.printStackTrace();
                throw BaseAuthenticationException.error(ErrorMessage.LOGIN_ERROR);

            }
        } else {
            throw BaseAuthenticationException.error(ErrorMessage.NO_JSON);
        }

    }


}
